import requests
import time
import random
import string
import hashlib
import os
import cv2
from requests_toolbelt import MultipartEncoder
session = requests.session()
token = "fd2bf2b851804f1e97618897315ba2dd"


def updata_Token():#获取accessToken
    url = r"https://test.whfciot.com/open/api/accessToken"  # 接口地址
    # appId
    appId = 'p4o4zpq0ymkx3vm3k12jj420w6z0f4jf'
    # 获取当前时间的时间戳,timestamp
    time_now = time.time()
    str_time = str(round(time_now * 1000))
    # 获取随机字符串（长度16）,randomStr
    def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
        return ''.join(random.choice(chars) for _ in range(size))
    randomStr = id_generator(16)
    # appKey
    appKey = '58jkl7viwxk6rt83eajepa23pu5ubi0w'
    # 加密计算签名,sign
    signature = 'appId=%s&timestamp=%s&randomStr=%s&appKey=%s' % (appId, str_time, randomStr, appKey)
    hl = hashlib.md5()
    hl.update(signature.encode(encoding='utf-8'))
    # 消息头数据
    headers = {
        'Content-Type': 'application/json',
    }
    # 请求参数Body
    payload = {'appId': appId,
               'timestamp': str_time,
               'randomStr': randomStr,
               'sign': hl.hexdigest(),
               }

    r = requests.post(url, json=payload, headers=headers)
    p = r.json()
    print(p)
    accessToken = p['data']['accessToken']
    return accessToken


def req_data(ip, tag, time_0):
    """
    :param ip: 摄像头编号
    :param tag: 标记
    :param time_0: 时间，输入：%Y-%m-%d;%H.%M.%S ，输出：%Y-%m-%d %H：%M：%S
    :return:
    """
    global token
    time_1 = time_0.replace(";", " ")
    time_1 = time_1.replace(".", ":")
    file = os.path.join(ip, time_0+'.png')
    m = MultipartEncoder(
        fields={
            'ip': str(ip),
            'tag': str(tag),
            'time': str(time_1),
            'image': (str(time_0)+'.png', open(file, 'rb'), 'image/png'),
        }
    )
    headers = {
        'Content-Type': m.content_type
    }
    url = 'https://test.whfciot.com/open/api/fvs/alg/result?accessToken=' + str(token)
    r = session.post(url, data=m, headers=headers)
    p = r.text
    m = p.encode('gb18030')
    if m != b'{"code":"200","msg":"\xb3\xc9\xb9\xa6"}':
        token = updata_Token()
        url = 'https://test.whfciot.com/open/api/fvs/alg/result?accessToken=' + str(token)
        m = MultipartEncoder(
            fields={
                'ip': str(ip),
                'tag': str(tag),
                'time': str(time_1),
                'image': (str(time_0) + '.png', open(file, 'rb'), 'image/png'),
            }
        )
        headers = {
            'Content-Type': m.content_type
        }
        r = session.post(url, data=m, headers=headers)
    return r.text

def remove(ip,time_0):
    file = os.path.join(ip, time_0+".png")
    if os.path.exists(file):
        os.remove(file)
        print("删除本地文件成功")

# 读取摄像头ip配置文件
def read_txt(ip_camera):
    """
    :param ip_camera:.txt 文件路径
    :return: 一个包含所有摄像头ip 的列表
    """
    file_object = open(ip_camera)
    try:
        file_str = file_object.read()
        file_context = file_str.splitlines()
        print(file_context)
    finally:
        file_object.close()
    return file_context

# 新建本地文件，存取图片
def new_file(ip_txt):
    """
    创建摄像头对应的文件夹
    :param ip_txt: .txt路径作为参数
    :return:
    """
    list = read_txt(ip_txt)
    for i in list:
        i = i.replace(":", ".")
        i = i.replace("/", "")
        if not os.path.exists('./' + str(i)):
            os.mkdir(str('./' + str(i)))
            print("创建文件夹成功")

# 传到数据库
def save_req(image,ip,tag):
    """
    安全帽调用：
    保存本地——上传——删除本地文件
    :param image:mat/numpy类型数据
    :param ip: 摄像头ip,函数read_text()返回值list中的元素
    :return:
    """
    ip = ip.replace(":", ".")
    ip = ip.replace("/", "")
    name = str(time.strftime("%Y-%m-%d;%H.%M.%S", time.localtime()))
    if not os.path.exists(ip):
        print("没有对应的存储路径")
        return
    cv2.imwrite(os.path.join(ip, name + ".png"), image)
    print("保存成功")
    # tag = tag
    txt = req_data(ip, tag, name)
    print(txt)
    remove(ip, name)



